﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace nhCore.db;

/// <summary>
/// 配置文件
/// </summary>
public class ElementConfig : ICloneable
{
    #region 常数定义
    public const string con_NOT = "NOT";
    public const string con_AVG = "AVG";
    public const string con_SUM = "SUM";
    #endregion

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [ForeignKey(nameof(Station))]
    [Display(Name = "站点Id")]
    public byte StationId { get; set; }

    [Display(Name = "要素名称"), MaxLength(20)]
    public string Name { get; set; } = null!;

    [Display(Name = "单位"), StringLength(20)]
    public string? Unit { get; set; }

    /// <summary>
    /// 映射Id，数据的最终去向。
    /// <remark>
    /// 站点读配置信息时，读本站点下及映射到本站点Id、及继承的所有配置。
    /// 界面显示以上所有配置。
    /// 保存时按本属性保存。
    /// </remark>
    /// </summary>
    [Display(Name = "映射站点Id")]
    public byte MappingStationId { get; set; }

    [Display(Name = "映射寄存器")]
    public short StationReg { get; set; }

    [Display(Name = "设备地址")]
    public byte DeviceAddress { get; set; }

    [Display(Name = "寄存器地址")]
    public short RegAddress { get; set; }

    [Display(Name = "功能码")]
    public byte FunctionCode { get; set; }

    [Display(Name = "数据类型"), StringLength(10)]
    public string? DataType { get; set; }

    [Display(Name = "小数位")]
    public int Digits { get; set; }

    [Display(Name = "统计方式"), StringLength(10)]
    public string Statistics { get; set; } = null!;

    [Display(Name = "要素类型"), StringLength(10)]
    public string? ElementType { get; set; }

    public double Max { get; set; }

    public double Min { get; set; }

    virtual public Station Site { get; } = null!;

    /// <summary>
    /// 数据类型
    /// </summary>
    [NotMapped]
    public NDataType NDataType { get; set; } = null!;

    [NotMapped]
    public string HandshakeFrame { get; set; } = null!;

    /// <summary>
    /// 构造函数
    /// </summary>
    public ElementConfig(string name, byte address, short reg, string dataFormat = NDataType.con_2ByteInt)
    {
        Name = name;
        DeviceAddress = address;
        RegAddress = reg;
        NDataType = new(dataFormat);
    }


    /// <summary>
    /// EFcore要求实体有无参数构造函数
    /// </summary>
    public ElementConfig()
    {
        NDataType = new(NDataType.con_2ByteInt);
    }

    /// <summary>
    /// 要素在数据表中的字段名
    /// </summary>
    /// <returns></returns>
    public string GetDataFieldName()
    {
        return $"A{StationReg}";
    }

    public object Clone()
    {
        return MemberwiseClone();
    }
}
